

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="https://gitee.com/wang-xuwen/wxwvaldz/raw/master/img/网站logo.png">
  <link rel="icon" href="https://gitee.com/wang-xuwen/wxwvaldz/raw/master/img/网站logo.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
    <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="Mysql管理以及事务管理">
  <meta name="author" content="小王">
  <meta name="keywords" content="Blog">
  <meta name="description" content="Mysql管理以及事务管理">
<meta property="og:type" content="article">
<meta property="og:title" content="Mysql初学习(2)">
<meta property="og:url" content="http://wang-xuwen.gitee.io/wang-xuwen.gitee.io/2021/12/21/Mysql%E5%88%9D%E5%AD%A6-2/index.html">
<meta property="og:site_name" content="菠萝头&#39;Blog">
<meta property="og:description" content="Mysql管理以及事务管理">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-12-21T07:24:23.000Z">
<meta property="article:modified_time" content="2021-12-21T07:31:41.697Z">
<meta property="article:author" content="wxwvaldz">
<meta property="article:tag" content="学习笔记">
<meta property="article:tag" content="点滴记录">
<meta name="twitter:card" content="summary_large_image">
  
  <title>Mysql初学习(2) - 菠萝头&#39;Blog</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_kmeydafke9r.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"wang-xuwen.gitee.io","root":"/","version":"1.8.12","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":1280684234,"leancloud":{"app_id":"JOpFiJtO4MLP5D7U1ojf6Ja3-gzGzoHsz","app_key":"2EinzSUFSXLtr3xK7WRCnpJL","server_url":null,"path":"window.location.pathname"}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.4.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>菠萝头&#39;Blog</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('https://gitee.com/wang-xuwen/wxwvaldz/raw/master/img/v2-39b206355387a08c5c86d3a6e41bb84f_r.jpg') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="Mysql初学习(2)">
              
            </span>

            
              <div class="mt-3">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-author" aria-hidden="true"></i>
      小王
    </span>
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2021-12-21 15:24" pubdate>
        2021年12月21日 下午
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      6.8k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      21 分钟
    </span>
  

  
  
    
      <!-- LeanCloud 统计文章PV -->
      <span id="leancloud-page-views-container" class="post-meta" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="leancloud-page-views"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">Mysql初学习(2)</h1>
            
              <p class="note note-info">
                
                  本文最后更新于：2 个月前
                
              </p>
            
            <div class="markdown-body">
              <p>Mysql管理以及事务管理</p>
<span id="more"></span>

<hr>
<h2 id="MYSQL"><a href="#MYSQL" class="headerlink" title="MYSQL"></a>MYSQL</h2><p>在安装完mysql之后，除了MySQL Server，即真正的MySQL服务器外，还附赠一个MySQL Client程序。MySQL Client是一个命令行客户端，可以通过MySQL Client登录MySQL，然后，输入SQL语句并执行。</p>
<p>MySQL Client和MySQL Server的关系如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs ascii">┌──────────────┐  SQL   ┌──────────────┐<br>│ MySQL Client │───────&gt;│ MySQL Server │<br>└──────────────┘  TCP   └──────────────┘<br></code></pre></td></tr></table></figure>

<p>在MySQL Client中输入的SQL语句通过TCP连接发送到MySQL Server。默认端口号是3306，即如果发送到本机MySQL Server，地址就是<code>127.0.0.1:3306</code>。</p>
<p>也可以只安装MySQL Client，然后连接到远程MySQL Server。假设远程MySQL Server的IP地址是<code>10.0.1.99</code>，那么就使用<code>-h</code>指定IP或域名：</p>
<figure class="highlight cmd"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs cmd">mysql -h <span class="hljs-number">10</span>.<span class="hljs-number">0</span>.<span class="hljs-number">1</span>.<span class="hljs-number">99</span> -u root -p<br></code></pre></td></tr></table></figure>

<h3 id="管理MySQL"><a href="#管理MySQL" class="headerlink" title="管理MySQL"></a>管理<strong>MySQL</strong></h3><p><strong>数据库</strong></p>
<p>在一个运行MySQL的服务器上，实际上可以创建多个数据库（Database）。要列出所有数据库，使用命令：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs mysql">mysql&gt; SHOW DATABASES;<br>+--------------------+<br>| Database           |<br>+--------------------+<br>| information_schema |<br>| mysql              |<br>| performance_schema |<br>| shici              |<br>| sys                |<br>| test               |<br>| school             |<br>+--------------------+<br></code></pre></td></tr></table></figure>

<p>其中，<code>information_schema</code>、<code>mysql</code>、<code>performance_schema</code>和<code>sys</code>是系统库，不要去改动它们。其他的是用户创建的数据库。</p>
<p>要创建一个新数据库，使用命令：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs mysql">mysql&gt; CREATE DATABASE test;<br>Query OK, 1 row affected (0.01 sec)<br></code></pre></td></tr></table></figure>

<p>要删除一个数据库，使用命令：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs mysql">mysql&gt; DROP DATABASE test;<br>Query OK, 0 rows affected (0.01 sec)<br></code></pre></td></tr></table></figure>

<p>注意：删除一个数据库将导致该数据库的所有表全部被删除。</p>
<p>对一个数据库进行操作时，要首先将其切换为当前数据库：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs mysql">mysql&gt; USE test;<br>Database changed<br></code></pre></td></tr></table></figure>

<p><strong>表</strong></p>
<p>列出当前数据库的所有表，使用命令：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs mysql">mysql&gt; SHOW TABLES;<br>+---------------------+<br>| Tables_in_test      |<br>+---------------------+<br>| classes             |<br>| statistics          |<br>| students            |<br>| students_of_class1  |<br>+---------------------+<br></code></pre></td></tr></table></figure>

<p>要查看一个表的结构，使用命令：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs mysql">mysql&gt; DESC students;<br>+----------+--------------+------+-----+---------+----------------+<br>| Field    | Type         | Null | Key | Default | Extra          |<br>+----------+--------------+------+-----+---------+----------------+<br>| id       | bigint(20)   | NO   | PRI | NULL    | auto_increment |<br>| class_id | bigint(20)   | NO   |     | NULL    |                |<br>| name     | varchar(100) | NO   |     | NULL    |                |<br>| gender   | varchar(1)   | NO   |     | NULL    |                |<br>| score    | int(11)      | NO   |     | NULL    |                |<br>+----------+--------------+------+-----+---------+----------------+<br>5 rows in set (0.00 sec)<br></code></pre></td></tr></table></figure>

<p>还可以使用以下命令查看创建表的SQL语句：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs mysql">mysql&gt; SHOW CREATE TABLE students;<br>+----------+-------------------------------------------------------+<br>| students | CREATE TABLE `students` (                             |<br>|          |   `id` bigint(20) NOT NULL AUTO_INCREMENT,            |<br>|          |   `class_id` bigint(20) NOT NULL,                     |<br>|          |   `name` varchar(100) NOT NULL,                       |<br>|          |   `gender` varchar(1) NOT NULL,                       |<br>|          |   `score` int(11) NOT NULL,                           |<br>|          |   PRIMARY KEY (`id`)                                  |<br>|          | ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 |<br>+----------+-------------------------------------------------------+<br>1 row in set (0.00 sec)<br></code></pre></td></tr></table></figure>

<p>创建表使用<code>CREATE TABLE</code>语句，而删除表使用<code>DROP TABLE</code>语句：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs mysql">mysql&gt; DROP TABLE students;<br>Query OK, 0 rows affected (0.01 sec)<br></code></pre></td></tr></table></figure>

<p>修改表就比较复杂。如果要给<code>students</code>表新增一列<code>birth</code>，使用：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">ALTER TABLE students ADD COLUMN birth VARCHAR(10) NOT NULL;<br></code></pre></td></tr></table></figure>

<p>要修改<code>birth</code>列，例如把列名改为<code>birthday</code>，类型改为<code>VARCHAR(20)</code>：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">ALTER TABLE students CHANGE COLUMN birth birthday VARCHAR(20) NOT NULL;<br></code></pre></td></tr></table></figure>

<p>要删除列，使用：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">ALTER TABLE students DROP COLUMN birthday;<br></code></pre></td></tr></table></figure>

<h3 id="实用mysql语句"><a href="#实用mysql语句" class="headerlink" title="实用mysql语句"></a>实用mysql语句</h3><p><strong>插入或替换</strong></p>
<p>如果我们希望插入一条新记录（INSERT），但如果记录已经存在，就先删除原记录，再插入新记录。此时，可以使用<code>REPLACE</code>语句，这样就不必先查询，再决定是否先删除再插入：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">REPLACE INTO students (id, class_id, name, gender, score) VALUES (1, 1, &#x27;小明&#x27;, &#x27;F&#x27;, 99);<br></code></pre></td></tr></table></figure>

<p>若<code>id=1</code>的记录不存在，<code>REPLACE</code>语句将插入新记录，否则，当前<code>id=1</code>的记录将被删除，然后再插入新记录。</p>
<h3 id="插入或更新"><a href="#插入或更新" class="headerlink" title="插入或更新"></a>插入或更新</h3><p>如果我们希望插入一条新记录（INSERT），但如果记录已经存在，就更新该记录，此时，可以使用<code>INSERT INTO ... ON DUPLICATE KEY UPDATE ...</code>语句：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">INSERT INTO students (id, class_id, name, gender, score) VALUES (1, 1, &#x27;小明&#x27;, &#x27;F&#x27;, 99) ON DUPLICATE KEY UPDATE name=&#x27;小明&#x27;, gender=&#x27;F&#x27;, score=99;<br></code></pre></td></tr></table></figure>

<p>若<code>id=1</code>的记录不存在，<code>INSERT</code>语句将插入新记录，否则，当前<code>id=1</code>的记录将被更新，更新的字段由<code>UPDATE</code>指定。</p>
<h3 id="插入或忽略"><a href="#插入或忽略" class="headerlink" title="插入或忽略"></a>插入或忽略</h3><p>如果我们希望插入一条新记录（INSERT），但如果记录已经存在，就啥事也不干直接忽略，此时，可以使用<code>INSERT IGNORE INTO ...</code>语句：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">INSERT IGNORE INTO students (id, class_id, name, gender, score) VALUES (1, 1, &#x27;小明&#x27;, &#x27;F&#x27;, 99);<br></code></pre></td></tr></table></figure>

<p>若<code>id=1</code>的记录不存在，<code>INSERT</code>语句将插入新记录，否则，不执行任何操作。</p>
<h3 id="快照"><a href="#快照" class="headerlink" title="快照"></a>快照</h3><p>如果想要对一个表进行快照，即复制一份当前表的数据到一个新表，可以结合<code>CREATE TABLE</code>和<code>SELECT</code>：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs mysql">-- 对class_id=1的记录进行快照，并存储为新表students_of_class1:<br>CREATE TABLE students_of_class1 SELECT * FROM students WHERE class_id=1;<br></code></pre></td></tr></table></figure>

<p>新创建的表结构和<code>SELECT</code>使用的表结构完全一致。</p>
<h3 id="写入查询结果集"><a href="#写入查询结果集" class="headerlink" title="写入查询结果集"></a>写入查询结果集</h3><p>如果查询结果集需要写入到表中，可以结合<code>INSERT</code>和<code>SELECT</code>，将<code>SELECT</code>语句的结果集直接插入到指定表中。</p>
<p>例如，创建一个统计成绩的表<code>statistics</code>，记录各班的平均成绩：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs mysql">CREATE TABLE statistics (<br>    id BIGINT NOT NULL AUTO_INCREMENT,<br>    class_id BIGINT NOT NULL,<br>    average DOUBLE NOT NULL,<br>    PRIMARY KEY (id)<br>);<br></code></pre></td></tr></table></figure>

<p>然后，我们就可以用一条语句写入各班的平均成绩：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">INSERT INTO statistics (class_id, average) SELECT class_id, AVG(score) FROM students GROUP BY class_id;<br></code></pre></td></tr></table></figure>

<p>确保<code>INSERT</code>语句的列和<code>SELECT</code>语句的列能一一对应，就可以在<code>statistics</code>表中直接保存查询的结果：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs mysql">&gt; SELECT * FROM statistics;<br>+----+----------+--------------+<br>| id | class_id | average      |<br>+----+----------+--------------+<br>|  1 |        1 |         86.5 |<br>|  2 |        2 | 73.666666666 |<br>|  3 |        3 | 88.333333333 |<br>+----+----------+--------------+<br>3 rows in set (0.00 sec)<br></code></pre></td></tr></table></figure>

<h3 id="强制使用指定索引"><a href="#强制使用指定索引" class="headerlink" title="强制使用指定索引"></a>强制使用指定索引</h3><p>在查询的时候，数据库系统会自动分析查询语句，并选择一个最合适的索引。但是很多时候，数据库系统的查询优化器并不一定总是能使用最优索引。如果我们知道如何选择索引，可以使用<code>FORCE INDEX</code>强制查询使用指定的索引。例如：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs mysql">&gt; SELECT * FROM students FORCE INDEX (idx_class_id) WHERE class_id = 1 ORDER BY id DESC;<br></code></pre></td></tr></table></figure>

<p>指定索引的前提是索引<code>idx_class_id</code>必须存在。</p>
<h2 id="事务"><a href="#事务" class="headerlink" title="事务"></a>事务</h2><ul>
<li>A：Atomic，原子性，将所有SQL作为原子工作单元执行，要么全部执行，要么全部不执行；</li>
<li>C：Consistent，一致性，事务完成后，所有数据的状态都是一致的，即A账户只要减去了100，B账户则必定加上了100；</li>
<li>I：Isolation，隔离性，如果有多个事务并发执行，每个事务作出的修改必须与其他事务隔离；</li>
<li>D：Duration，持久性，即事务完成后，对数据库数据的修改被持久化存储。</li>
</ul>
<p>隐式事务：单条mysql语句，数据库自动将其当作一个事务执行</p>
<p>显式事务：手动把多条SQL语句作为一个事务执行，使用<code>BEGIN</code>开启一个事务，使用<code>COMMIT</code>提交一个事务</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs mysql">BEGIN;<br>UPDATE accounts SET balance = balance - 100 WHERE id = 1;<br>UPDATE accounts SET balance = balance + 100 WHERE id = 2;<br>COMMIT;<br></code></pre></td></tr></table></figure>

<p><code>COMMIT</code>是指提交事务，即试图把事务内的所有SQL所做的修改永久保存。如果<code>COMMIT</code>语句执行失败了，整个事务也会失败。</p>
<p>有些时候，我们希望主动让事务失败，这时，可以用<code>ROLLBACK</code>回滚事务，整个事务会失败：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs mysql">BEGIN;<br>UPDATE accounts SET balance = balance - 100 WHERE id = 1;<br>UPDATE accounts SET balance = balance + 100 WHERE id = 2;<br>ROLLBACK;<br></code></pre></td></tr></table></figure>

<h3 id="隔离级别"><a href="#隔离级别" class="headerlink" title="隔离级别"></a>隔离级别</h3><p>对于两个并发执行的事务，如果涉及到操作同一条记录的时候，可能会发生问题。因为并发操作会带来数据的不一致性，包括脏读、不可重复读、幻读等。数据库系统提供了隔离级别来让我们有针对性地选择事务的隔离级别，避免数据不一致的问题。</p>
<p>SQL标准定义了4种隔离级别，分别对应可能出现的数据不一致的情况：</p>
<table>
<thead>
<tr>
<th align="left">Isolation Level</th>
<th align="left">脏读（Dirty Read）</th>
<th align="left">不可重复读（Non Repeatable Read）</th>
<th align="left">幻读（Phantom Read）</th>
</tr>
</thead>
<tbody><tr>
<td align="left">Read Uncommitted</td>
<td align="left">Yes</td>
<td align="left">Yes</td>
<td align="left">Yes</td>
</tr>
<tr>
<td align="left">Read Committed</td>
<td align="left">-</td>
<td align="left">Yes</td>
<td align="left">Yes</td>
</tr>
<tr>
<td align="left">Repeatable Read</td>
<td align="left">-</td>
<td align="left">-</td>
<td align="left">Yes</td>
</tr>
<tr>
<td align="left">Serializable</td>
<td align="left">-</td>
<td align="left">-</td>
<td align="left">-</td>
</tr>
</tbody></table>
<h3 id="Read-Uncommitted"><a href="#Read-Uncommitted" class="headerlink" title="Read Uncommitted"></a>Read Uncommitted</h3><p>读取到的数据为上一个事务修改数据并且该数据回滚，数据失效，也就是脏数据</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs mysql">mysql&gt; select * from students;<br>+----+-------+<br>| id | name  |<br>+----+-------+<br>|  1 | Alice |<br>+----+-------+<br>1 row in set (0.00 sec)<br></code></pre></td></tr></table></figure>

<table>
<thead>
<tr>
<th align="left">时刻</th>
<th align="left">事务A</th>
<th align="left">事务B</th>
</tr>
</thead>
<tbody><tr>
<td align="left">1</td>
<td align="left">SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;</td>
<td align="left">SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;</td>
</tr>
<tr>
<td align="left">2</td>
<td align="left">BEGIN;</td>
<td align="left">BEGIN;</td>
</tr>
<tr>
<td align="left">3</td>
<td align="left">UPDATE students SET name = ‘Bob’ WHERE id = 1;</td>
<td align="left"></td>
</tr>
<tr>
<td align="left">4</td>
<td align="left"></td>
<td align="left">SELECT * FROM students WHERE id = 1;</td>
</tr>
<tr>
<td align="left">5</td>
<td align="left">ROLLBACK;</td>
<td align="left"></td>
</tr>
<tr>
<td align="left">6</td>
<td align="left"></td>
<td align="left">SELECT * FROM students WHERE id = 1;</td>
</tr>
<tr>
<td align="left">7</td>
<td align="left"></td>
<td align="left">COMMIT;</td>
</tr>
</tbody></table>
<p>当事务A执行完第3步时，它更新了<code>id=1</code>的记录，但并未提交，而事务B在第4步读取到的数据就是未提交的数据。</p>
<p>随后，事务A在第5步进行了回滚，事务B再次读取<code>id=1</code>的记录，发现和上一次读取到的数据不一致，这就是脏读。</p>
<p>可见，在Read Uncommitted隔离级别下，一个事务可能读取到另一个事务更新但未提交的数据，这个数据有可能是脏数据。</p>
<h3 id="Read-Committed"><a href="#Read-Committed" class="headerlink" title="Read Committed"></a>Read Committed</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs mysql">mysql&gt; select * from students;<br>+----+-------+<br>| id | name  |<br>+----+-------+<br>|  1 | Alice |<br>+----+-------+<br>1 row in set (0.00 sec)<br></code></pre></td></tr></table></figure>

<table>
<thead>
<tr>
<th align="left">时刻</th>
<th align="left">事务A</th>
<th align="left">事务B</th>
</tr>
</thead>
<tbody><tr>
<td align="left">1</td>
<td align="left">SET TRANSACTION ISOLATION LEVEL READ COMMITTED;</td>
<td align="left">SET TRANSACTION ISOLATION LEVEL READ COMMITTED;</td>
</tr>
<tr>
<td align="left">2</td>
<td align="left">BEGIN;</td>
<td align="left">BEGIN;</td>
</tr>
<tr>
<td align="left">3</td>
<td align="left"></td>
<td align="left">SELECT * FROM students WHERE id = 1;</td>
</tr>
<tr>
<td align="left">4</td>
<td align="left">UPDATE students SET name = ‘Bob’ WHERE id = 1;</td>
<td align="left"></td>
</tr>
<tr>
<td align="left">5</td>
<td align="left">COMMIT;</td>
<td align="left"></td>
</tr>
<tr>
<td align="left">6</td>
<td align="left"></td>
<td align="left">SELECT * FROM students WHERE id = 1;</td>
</tr>
<tr>
<td align="left">7</td>
<td align="left"></td>
<td align="left">COMMIT;</td>
</tr>
</tbody></table>
<p>当事务B第一次执行第3步的查询时，得到的结果是<code>Alice</code>，随后，由于事务A在第4步更新了这条记录并提交，所以，事务B在第6步再次执行同样的查询时，得到的结果就变成了<code>Bob</code>，因此，在Read Committed隔离级别下，事务不可重复读同一条记录，因为很可能读到的结果不一致。</p>
<h3 id="Repeatable-Read"><a href="#Repeatable-Read" class="headerlink" title="Repeatable Read"></a>Repeatable Read</h3><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs mysql">mysql&gt; select * from students;<br>+----+-------+<br>| id | name  |<br>+----+-------+<br>|  1 | Alice |<br>+----+-------+<br>1 row in set (0.00 sec)<br></code></pre></td></tr></table></figure>

<p>事务B在第3步第一次读取<code>id=99</code>的记录时，读到的记录为空，说明不存在<code>id=99</code>的记录。随后，事务A在第4步插入了一条<code>id=99</code>的记录并提交。事务B在第6步再次读取<code>id=99</code>的记录时，读到的记录仍然为空，但是，事务B在第7步试图更新这条不存在的记录时，竟然成功了，并且，事务B在第8步再次读取<code>id=99</code>的记录时，记录出现了。</p>
<p>可见，幻读就是没有读到的记录，以为不存在，但其实是可以更新成功的，并且，更新成功后，再次读取，就出现了。</p>
<h3 id="Serializable"><a href="#Serializable" class="headerlink" title="Serializable"></a>Serializable</h3><p>Serializable是最严格的隔离级别。在Serializable隔离级别下，所有事务按照次序依次执行，因此，脏读、不可重复读、幻读都不会出现。</p>
<p>虽然Serializable隔离级别下的事务具有最高的安全性，但是，由于事务是串行执行，所以效率会大大下降，应用程序的性能会急剧降低。如果没有特别重要的情景，一般都不会使用Serializable隔离级别。</p>
<h3 id="默认隔离级别"><a href="#默认隔离级别" class="headerlink" title="默认隔离级别"></a>默认隔离级别</h3><p>如果没有指定隔离级别，数据库就会使用默认的隔离级别。在MySQL中，如果使用InnoDB，默认的隔离级别是Repeatable Read。</p>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">学习笔记</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">学习笔记</a>
                    
                      <a class="hover-with-bg" href="/tags/%E7%82%B9%E6%BB%B4%E8%AE%B0%E5%BD%95/">点滴记录</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载先请联系作者且注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2021/12/21/%E5%85%B3%E4%BA%8E%E8%85%BE%E8%AE%AF%E4%BA%91%E7%9A%84%E6%97%A0%E5%BF%A7%E8%AE%A1%E5%88%92/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">关于腾讯云的无忧计划</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2021/12/20/Mysql%E5%88%9D%E5%AD%A6-1/">
                        <span class="hidden-mobile">Mysql初学习(1)</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
              <!-- Comments -->
              <article class="comments" id="comments" lazyload>
                
                  
                
                
  <div id="waline"></div>
  <script type="text/javascript">
    Fluid.utils.loadComments('#waline', function() {
      Fluid.utils.createScript('https://cdn.jsdelivr.net/npm/@waline/client@1/dist/Waline.min.js', function() {
        var options = Object.assign(
          {"serverURL":"https://blog-api-fawn.vercel.app/","path":"window.location.pathname","placeholder":"想说的话~","meta":["nick","mail","link"],"requiredMeta":["nick"],"lang":"zh-CN","emoji":["https://cdn.jsdelivr.net/gh/walinejs/emojis/weibo"],"dark":"html[data-user-color-scheme=\"dark\"]","avatar":"retro","avatarCDN":"https://seccdn.libravatar.org/avatar/","avatarForce":false,"wordLimit":0,"pageSize":10,"highlight":true},
          {
            el: '#waline',
            path: window.location.pathname
          }
        )
        new Waline(options);
        Fluid.utils.waitElementVisible('#waline .vcontent', () => {
          Fluid.plugins.initFancyBox('#waline .vcontent img:not(.vemoji)');
        })
      });
    });
  </script>
  <noscript>Please enable JavaScript to view the comments</noscript>


              </article>
            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
    <!--  <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a>  -->
    <div>
      <span id="timeDate">载入天数...</span>
      <span id="times">载入时分秒...</span>
      <script>
      var now = new Date();
      function createtime(){
          var grt= new Date("12/9/2021 20:13:49");//此处修改你的建站时间或者网站上线时间
          now.setTime(now.getTime()+250);
          days = (now - grt ) / 1000 / 60 / 60 / 24;
          dnum = Math.floor(days);
          hours = (now - grt ) / 1000 / 60 / 60 - (24 * dnum);
          hnum = Math.floor(hours);
          if(String(hnum).length ==1 ){
              hnum = "0" + hnum;
          }
          minutes = (now - grt ) / 1000 /60 - (24 * 60 * dnum) - (60 * hnum);
          mnum = Math.floor(minutes);
          if(String(mnum).length ==1 ){
                    mnum = "0" + mnum;
          }
          seconds = (now - grt ) / 1000 - (24 * 60 * 60 * dnum) - (60 * 60 * hnum) - (60 * mnum);
          snum = Math.round(seconds);
          if(String(snum).length ==1 ){
                    snum = "0" + snum;
          }
          document.getElementById("timeDate").innerHTML = "🚀 &nbsp此博客网站已经在夹缝中生存了"+"<br/>"+dnum+"&nbsp天";  //此次自定义显示内容
          document.getElementById("times").innerHTML = hnum + "&nbsp小时&nbsp" + mnum + "&nbsp分&nbsp" + snum + "&nbsp秒";
      }  //此次自定义显示内容
      setInterval("createtime()",250);
      </script>
    </div>
  </div>
  
  <div class="statistics">
    
    

    
      
        <!-- LeanCloud 统计PV -->
        <span id="leancloud-site-pv-container" style="display: none">
            总访问量 
            <span id="leancloud-site-pv"></span>
             次
          </span>
      
      
        <!-- LeanCloud 统计UV -->
        <span id="leancloud-site-uv-container" style="display: none">
            总访客数 
            <span id="leancloud-site-uv"></span>
             人
          </span>
      

    
  </div>


  

  
    <!-- cnzz Analytics Icon -->
    <span id="cnzz_stat_icon_1280684234" style="display: none"></span>
  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  




  <script defer src="/js/leancloud.js" ></script>



  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
      typing(title)
      
    })(window, document);
  </script>












  

  

  

  

  

  
    <!-- cnzz Analytics -->
    <script defer src="//s4.cnzz.com/z_stat.php?id=1280684234&show=pic"
            type="text/javascript"></script>
  





<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"jsonPath":"/live2dw/assets/assets/koharu.model.json"},"display":{"position":"left","width":150,"height":300,"hOffset":0,"vOffset":-20},"mobile":{"show":true},"react":{"opacity":1},"log":false});</script></body>
</html>
